import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
from dns_fun import dns_xm


def send_mail(mailfrom, mailto, subject, body, body_type='plain', att_files_path=None, pic_path=None,cc=None, bcc=None):

    if att_files_path:
        message = MIMEMultipart()
        ##mail body
        message.attach(MIMEText(body, 'html', 'utf-8'))
        ##attachment1
        for f_path in att_files_path:
            #print f_path
            att1 = MIMEText(open(f_path, 'rb').read(), 'base64', 'utf-8')
            att1["Content-Type"] = 'application/octet-stream'
            filename = f_path.split('/')[-1]
            att1["Content-Disposition"] = 'attachment; filename=%s' % filename
            message.attach(att1)
        if pic_path:
            msgPic = MIMEMultipart('alternative')
            message.attach(msgPic)

            msgPic.attach(MIMEText(body, 'html', 'utf-8'))

            fp = open(pic_path, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

            msgImage.add_header('Content-ID', '<image1>')
            message.attach(msgImage)


    else:
        message = MIMEText(body, body_type, 'utf-8')

    message['from'] = mailfrom
    message['To'] = ','.join(mailto)
    message['Subject'] = Header(subject, 'utf-8')

    if cc:
        message['Cc'] = ','.join(cc)
        mailto.extend(cc)
    if bcc:
        message['bCc'] = ','.join(bcc)
        mailto.extend(bcc)

    user_addr_dic, domain_xm_dic = get_receivers_xm(mailto)

    for dm1 in user_addr_dic:
        for dm2 in domain_xm_dic:
            if dm1 == dm2:
                mail_server_xm = domain_xm_dic[dm2]
                receivers_lst = user_addr_dic[dm1]
                #print mail_server_xm
                #print receivers_lst
                try:
                    smtpobj = smtplib.SMTP('localhost')
                    #smtpobj = smtplib.SMTP(mail_server_xm)
                    smtpobj.set_debuglevel(0)
                    smtpobj.sendmail(mailfrom, receivers_lst, message.as_string())
                    print "send the mail to %s complete" % ','.join(receivers_lst)
                except Exception as e:
                    print e
                    print mail_server_xm
                    print "send the mail to %s failure" % ','.join(receivers_lst)


def get_receivers_xm(addr_lst):
    domain_useraddr_dic={}
    domain_xm_dic = {}
    domain_lst = []
    for addr in addr_lst:
        mail_addr = [addr]
        if "@" in addr:
            domain = addr.split('@')[-1]
            domain_lst.append(domain)
            if domain_useraddr_dic.has_key(domain):
                domain_useraddr_dic[domain].extend(mail_addr)
            else:
                domain_useraddr_dic[domain] = mail_addr

    for domain in set(domain_lst):
        domain_xm_dic[domain] = dns_xm(domain)

    return domain_useraddr_dic, domain_xm_dic


if __name__ == "__main__":
    mailfrom = 'ET.report@sh-dev03.com'
    mailto = ['xiangfeng.bu@nokia-sbell.com']
    # cc = ['119912808@qq.com']
    # bcc = ['']
    subject = "send Email"
    file_path = "/var/lib/libvirt/log/xbu/et_test/not_analyzed_2018-02-07-09-32.log"
    with open(file_path, 'r') as f:
        table_info = f.read()

    gen_html = '<html>' \
               '<head></head>' \
               '<body><p>Hi All!<br><br>' \
               'Not Analysis Test Cases to be completed, please take actions!!<br>' \
               '<table border="2" style="TABLE-LAYOUT: fixed" border="1" cellspacing="0" cellpadding="0" width="800">' \
               '{0}</table>' \
               '</body></html>'.format(table_info)
    file_html = file_path+'.html'
    with open(file_html, 'w') as f:
        f.write(gen_html)
    file_path_list = ["/var/lib/libvirt/log/xbu/et_test/not_analyzed_2018-02-07-09-32.log",
                      "/var/lib/libvirt/log/xbu/et_test/not_analyzed_2018-02-07-09-04.log"
                      ]
    send_mail(mailfrom=mailfrom, mailto=mailto, subject=subject, body=gen_html, body_type='html', att_files_path=file_path_list)

